package com.oig.sys.msg.service.impl;

import com.oig.common.constants.CommonEnum;
import com.oig.common.exception.BadRequestException;
import com.oig.sys.msg.dao.ITbMqConfigDao;
import com.oig.sys.msg.dto.MqConfigDto;
import com.oig.sys.msg.entity.TbMqConfig;
import com.oig.sys.msg.service.ITbMqConfigService;
import com.oig.sys.msg.vo.MqConfigVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author wuxl
 */
@Service
public class TbMqConfigServiceImpl implements ITbMqConfigService {

	private final ITbMqConfigDao tbMqConfigDao;

	@Autowired
	public TbMqConfigServiceImpl(ITbMqConfigDao tbMqConfigDao){
		 this.tbMqConfigDao = tbMqConfigDao;
	}

	@Transactional
	@Override
	public MqConfigVo addMqConfig(MqConfigDto mqConfigDto){
		TbMqConfig mqConfig = this.tbMqConfigDao.getOkMqConfig(mqConfigDto.getRelationType()) ;
		if (mqConfig!=null){
			throw new BadRequestException("已有配置，重复了") ;
		}
		mqConfig = new TbMqConfig();
		BeanUtils.copyProperties(mqConfigDto, mqConfig, "id");
		mqConfig.setStatus(CommonEnum.CommonStatusEnum.OK.getCode());
		this.tbMqConfigDao.save(mqConfig);
		return buildVo(mqConfig);
	}

	private MqConfigVo buildVo(TbMqConfig config){
		MqConfigVo vo = new MqConfigVo();
		BeanUtils.copyProperties(config, vo);
		return vo;
	}

	@Transactional
	@Override
	public MqConfigVo updateMqConfig(MqConfigDto mqConfigDto){
		TbMqConfig mqConfig = this.tbMqConfigDao.getMqConfigById(mqConfigDto.getId()) ;
		this.checkConfig(mqConfig);
		mqConfig.setProducerExchange(mqConfigDto.getProducerExchange());
		mqConfig.setProducerKey(mqConfigDto.getProducerKey());
		this.tbMqConfigDao.save(mqConfig);
		return buildVo(mqConfig);
	}

	private void checkConfig(TbMqConfig mqConfig){
		if (mqConfig==null){
			throw new BadRequestException("配置不存在") ;
		}
		if (CommonEnum.CommonStatusEnum.DEL.getCode().equals(mqConfig.getStatus())){
			throw new BadRequestException("配置已删除") ;
		}
	}

	@Transactional
	@Override
	public void cancelMqConfig(Integer id){
		TbMqConfig mqConfig = this.tbMqConfigDao.getMqConfigById(id) ;
		this.checkConfig(mqConfig);
		mqConfig.setStatus(CommonEnum.CommonStatusEnum.DEL.getCode());
		this.tbMqConfigDao.save(mqConfig);
	}


	@Override
	public MqConfigVo getMqConfig(Integer id) {
		TbMqConfig mqConfig = this.tbMqConfigDao.getMqConfigById(id) ;
		if (mqConfig==null){
			throw new BadRequestException("配置不存在") ;
		}
		return this.buildVo(mqConfig);
	}

	@Override
	public MqConfigVo getOkMqConfig(String relationType) {
		TbMqConfig config = this.tbMqConfigDao.getOkMqConfig(relationType) ;
		if (config==null) return null;
		return buildVo(config);
	}
}
